package com.xca.znb.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.xca.znb.R;
import com.xca.znb.adapter.ProcurementManagerAdapter;
import com.xca.znb.adapter.SearchAdapter;
import com.xca.znb.entity.Collect;
import com.xca.znb.entity.Goods;
import com.xca.znb.entity.Procurement;
import com.xca.znb.entity.User;
import com.xca.znb.model.impl.EnterStoreImpl;
import com.xca.znb.presenter.EnterStorePresenter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class EnterStoreActivity extends AppCompatActivity implements View.OnClickListener{
    private ImageView backBtn ;
    private ImageView userImg ;

    private TextView userName , userPhone , userLocal , salesGoods , procurementGoods;
    private ListView mgList ;
    private ImageButton talkSales , callSales ;

    private EnterStorePresenter presenter ;
    private List<Goods> goodsList ;
    private List<Procurement> procurementList ;
    private SearchAdapter goodsAdapter ;
    private ProcurementManagerAdapter procurementAdapter ;
    private CheckBox collectStore ;
    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.enter_store);
        initView();
        EnterStoreImpl enterStoreImpl = new EnterStoreImpl(this);
        presenter = new EnterStorePresenter(enterStoreImpl);
        salesGoods.setSelected(true);
        salesGoods.setOnClickListener(this);
        procurementGoods.setOnClickListener(this);

        Intent intent = getIntent() ;
        String getSalesPhone = intent.getStringExtra("salesPhone");


        goodsList = presenter.getGoodsByPhone(getSalesPhone);
        procurementList = presenter.getProcurementByPhone(getSalesPhone);

        goodsAdapter = new SearchAdapter(this , goodsList);
        mgList.setAdapter(goodsAdapter);
        goodsAdapter.notifyDataSetChanged();


        mgList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (salesGoods.isSelected()){
                    TextView showId = view.findViewById(R.id.searchItem_goods_show_goodsId) ;
                    String sId = showId.getText().toString();

                    int goodId = Integer.parseInt(sId);
                    SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
                    String phone = sharedPreferences.getString("phone" , "");
                    LocalDateTime nowTime = LocalDateTime.now();
                    String secTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

                    Intent intent = new Intent(EnterStoreActivity.this , GoodsDetailActivity.class) ;
                    intent.putExtra("goodsId" , sId) ;

                    presenter.addOrUpdateFoot(goodId,phone,secTime);
                    startActivity(intent);
                } else if (procurementGoods.isSelected()) {
                    TextView showId = view.findViewById(R.id.procurement_manager_id);
                    String sId = showId.getText().toString() ;
                    Intent intent = new Intent(EnterStoreActivity.this , ProcurementMessage.class);
                    intent.putExtra("pManToMeId" , sId);

                    intent.putExtra("sales_phone" , getSalesPhone);
                    startActivity(intent);
                }
            }
        });



        User user = presenter.getUser(getSalesPhone);
        String img = user.getConcern();
        String name = user.getName();
        String local = user.getLocal();
        Glide.with(this)
                        .load(img)
                                .into(userImg);
        //userImg.setImageResource(R.drawable.friends_b);
        userPhone.setText(getSalesPhone);
        userName.setText(name);
        userLocal.setText(local);
        //Toast.makeText(this, user.getPhone(), Toast.LENGTH_SHORT).show();

        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");

        talkSales.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取当前时间：精确到秒
                LocalDateTime nowTime = LocalDateTime.now();
                String secTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                presenter.addNewsletter(phone , getSalesPhone , secTime);
                Intent intent1 = new Intent(EnterStoreActivity.this , MessageActivity.class) ;
                intent1.putExtra("goods_send" , phone);
                intent1.putExtra("goods_receive" , getSalesPhone);
                startActivity(intent1);
            }
        });
        callSales.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCallConfirmationDialog(getSalesPhone); // 替换为实际电话号码
            }
        });
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


        collectStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String type = "store" ;
                Collect collect = presenter.getCollect(getSalesPhone , type , phone) ;
                if (collectStore.isChecked()){
                    if (collect == null){
                        presenter.addCollect(getSalesPhone , type , phone);
                        Collect collect1 = presenter.getCollect(getSalesPhone , type , phone) ;
                        if (collect1 != null){
                            Toast.makeText(EnterStoreActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                }else {
                    if (collect != null){
                        presenter.delCollect(collect.getId());
                        Collect collect1 = presenter.getCollect(getSalesPhone , type , phone) ;
                        if (collect1 == null){
                            Toast.makeText(EnterStoreActivity.this, "取消收藏", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        });
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.enter_store_sales_sale){
            salesGoods.setSelected(true);
            procurementGoods.setSelected(false);

            Intent intent = getIntent() ;
            String getSalesPhone = intent.getStringExtra("salesPhone");
            goodsList = presenter.getGoodsByPhone(getSalesPhone);
            goodsAdapter = new SearchAdapter(this , goodsList);
            mgList.setAdapter(goodsAdapter);
            goodsAdapter.notifyDataSetChanged();
        } else if (v.getId() == R.id.enter_store_sales_procurement) {
            salesGoods.setSelected(false);
            procurementGoods.setSelected(true);

            Intent intent = getIntent() ;
            String getSalesPhone = intent.getStringExtra("salesPhone");
            procurementList = presenter.getProcurementByPhone(getSalesPhone);
            procurementAdapter = new ProcurementManagerAdapter(this , procurementList);
            mgList.setAdapter(procurementAdapter);
            procurementAdapter.notifyDataSetChanged();
        }
    }

    private void showCallConfirmationDialog(String phoneNumber) {
        // 检查拨打电话的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CALL_PHONE},
                    1);
        } else {
            confirmCall(phoneNumber);
        }
    }
    // 确认拨打电话
    private void confirmCall(String phoneNumber) {
        new AlertDialog.Builder(this)
                .setTitle("拨打电话")
                .setMessage("您确定要拨打"+ phoneNumber +"这个电话吗？")
                .setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Intent callIntent = new Intent(Intent.ACTION_CALL);
                        callIntent.setData(Uri.parse("tel:" + phoneNumber));
                        startActivity(callIntent);
                    }
                })
                .setNegativeButton("取消", null).show();
    }
    private void initView(){
        backBtn = findViewById(R.id.enter_store_back) ;
        userImg = findViewById(R.id.enter_store_user_concern);
        userName = findViewById(R.id.enter_store_show_name);
        userPhone = findViewById(R.id.enter_store_show_phone);
        userLocal = findViewById(R.id.enter_store_user_local);
        salesGoods = findViewById(R.id.enter_store_sales_sale);
        procurementGoods = findViewById(R.id.enter_store_sales_procurement);
        mgList = findViewById(R.id.enter_store_about_goods);
        talkSales = findViewById(R.id.enter_store_talk);
        callSales = findViewById(R.id.enter_store_call);
        collectStore = findViewById(R.id.enter_store_addCollection);
    }
    //以下是关于收藏功能的书写
    private void collectData(){
        String type = "store" ;//收藏类型
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");//收藏user
        Intent intent = getIntent() ;
        String gId = intent.getStringExtra("salesPhone");//收藏Id

        Collect collect = presenter.getCollect(gId , type , phone) ;
        collectStore.setChecked(collect != null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        collectData();
    }
}
